/**
 * 创建会话Dialog.
 */
var ChatGroupDialog = (function(){       
    /**
     * 构造函数.
     */ 
    var _groupManageDialog = function(config){
        var _this = this;
      
        this.setProps({
            size : {
                width : 865,
                height : 500
            },
            buttons : [
                {   
                    props : 'back|' + lan('dialog.buttons.back'),    
                    handler : function($btnObj){
                        _this.showCard('groupFormS1').switchDialogButtons(['next']).setTitle(_this.config['title'] + ' 1/2');
                    }
                }, {   
                    props : 'save|' + lan('dialog.buttons.save'),    
                    handler : function($btnObj) {
                        if(!ujs.browser.form.validate(_this.$wrapper)){
                            return false;
                        }
                        //保存或更新.  
                        var formData = _this.getFormData();
                        _this.showMask('');
                        if(!_this.chatGroupID){
                            _this.showMask(lan('common.creating', lan('app.im.chat.name')));
                            page.biz.createChatGroup(formData, function(msg){                                
                                page.biz.addChatGroupLocal(msg);                                    
                                sessionList.startSession(msg['te']['id']);
                                _this.remove();                                
                            }, function(){
                                _this.hideMask();        
                            });
                        } else {
                            _this.showMask(lan('common.updating', lan('app.im.chat.name')));
                            page.biz.updateChatGroup(_this.chatGroupID, formData, function(msg){
                                bubble.msg(lan('common.updateDone', lan('app.im.chat.name')));                                   
                                _this.remove();                              
                            }, function(){
                                _this.hideMask();        
                            });
                        }                                         
                    }
                }, {   
                    props : 'next|' + lan('dialog.buttons.next'),    
                    handler : function($btnObj){                        
                        _this.showCard('groupFormS2');
                        _this.switchDialogButtons(['save', 'back']);    
                        _this.setTitle(_this.config['title'] + ' 2/2');
                        
                        if(_this.config['mode'] != 'edit'){
                            var mems = _this.memberSelector.memberList.getOptions().slice(0,2);
                            var defTitle = mems.map(function(item, index){return item.text;}).join(', ');
                            if( _this.memberSelector.memberList.getOptions().length > 1){
                                defTitle += ' ...';
                            }
                            _this.$wrapper.find('.chatGroupTitle').val(defTitle);
                        }
                    }                               
                }
            ]
        });        
        
        if(this.config['isBase'] === true){                
            this.groupFormS1();
            this.groupFormS2();
        } else {
            this.groupFormS2();
            this.groupFormS1();
        }
                
        if(this.config['isBase'] === true){
            //只改基础信息.
            (function(){  
                _this.toggleAdvancedProps(false);
                _this.switchDialogButtons(['save']);
                _this.setTitle(_this.config['title']);                
            }).defer();
        } else {
            this.switchDialogButtons(_this.config['mode'] != 'edit' ? [] : ['save']);
        }
    }.extend(ujs.ui.Dialog);    
    /**
     * step 1.
     */
    _groupManageDialog.prototype.groupFormS1 = function(){
        var _this = this;        
        this.addDialogContent(ChatGroupDialogView.chatGroupForm, function($dialogContent) {                        
            _this.$selectUserTip = $dialogContent.find('.su'); 
            //member selector            
            _this.memberSelector = new MemberSelector($dialogContent.find('.memberSelector2'), {
                size : {
                    width : 654,
                    height : 120
                },
                treeType : 'adminchat',
                clickable : (function(){
                    if(_this.config['mode'] === 'edit'){                        
                        var entity = page.chatGroupStore.getItem(_this.config['teid']);
                        if(entity.perm.adm && entity.te.creator.id == ujs.util.session.getCurrentUserID()){
                            return true;
                        } else {
                            _this.$selectUserTip.remove();
                            return false;
                        }
                    } else {
                        //添加模式
                        return true;
                    }
                })(),
                mode : 'expand',
                root : _this.config['root'],
                exclusion : [ujs.util.session.getCurrentUserID()],
                events : {
                    'change' : function(){
                        _this.toggleAdvancedProps();
                    }
                }
            });    
            if(_this.config['initMembers']){
                _this.memberSelector.addMembers(_this.config['initMembers']);
            }           
            //编辑模式.
            if(_this.config['mode'] === 'edit'){                
                _this.initFormData(_this.config['teid']);
                _this.toggleAdvancedProps(true);
            } else {
                _this.toggleAdvancedProps(false);
            }
            if(_this.config['isBase'] === true){
                _this.toggleAdvancedProps(false);
            }
        });
    };   
    
    /**
     * step 2.
     */
    _groupManageDialog.prototype.groupFormS2 = function(){
        var _this = this;        
        this.addDialogContent(ChatGroupDialogView.chatGroupForm2, function($dialogContent) {
            _this.$memPanel = $dialogContent.find('.memberPanel');
            //chat group icon 选择控件.
            _this.iconObj = $dialogContent.find('#icon').singleImgUploader({                
                uploadImmediately : false,
                style : 'innerIcon',
                width : 60,
                height : 60, 
                toolbar : false,
                value : '/ujs/images/im/user-group/user-group-256.jpg'                
            }).data('singleImgUploader');
            
            _this.optionSelectorGrouper2 = $dialogContent.find('#props2').stringList({
                theme : 'checkboxGroup',
                direction : 'v',
                deletable : false,
                addable : false,                      
                data : 'Do not allow individual chat|not,Allow reply to Broadcaster|reply,Display Location|allowLocation'
            }).data('stringList');
            _this.optionSelectorGrouper2.filter(['not', 'allowLocation']);
                        
            _this.optionSelectorGrouper = $dialogContent.find('#props').grouper({
                type : 'radiobox',                
                value : 'normal',
                theme : 'radioGroup',
                items : [
                    {
                        id : 'normal',
                        title : lan('app.im.chat.type.normal')
                    },{
                        id : 'destruct',
                        title : lan('app.im.chat.type.destruct')
                    },{
                        id : 'broadcast',
                        title : lan('app.im.chat.type.broadcast')
                    }
                ], 
                onClick : function(val, isSelected){
                    if(isSelected && val == 'broadcast'){
                        _this.optionSelectorGrouper2.filter(['reply']);
                    } else {
                        _this.optionSelectorGrouper2.filter(['not', 'allowLocation']);
                    }
                }                 
            }).data('grouper');
                                    
            if(_this.config['mode'] === 'edit'){
                $dialogContent.find('.propsRow').hide();
            }                            
        });
    };   
     
    /**
     * 初始化表单数据。
     */
    _groupManageDialog.prototype.initFormData = function(chatID){
        var _this = this;
        _this.chatGroupID = chatID;
        $.ajax({
            url : '/apis/chat/{topicEntityId}'.format({
                topicEntityId : chatID
            }) 
        }).then(ujs.hr(function(msg){
            ujs.browser.form.setValues(_this.$wrapper, msg['te']);                
            _this.memberSelector.addMembers(msg.te.participants).setAdmins(msg.te.adminUserIds);
            _this.initPerm(msg['te']);
            if(_this.config['isBase'] === true){
                _this.toggleAdvancedProps(false);
                _this.showCard('groupFormS2');
                _this.$wrapper.find('.flagFields').show();
            }
        }));
    };    
    
    /**
     * 初始化权限.
     */
    _groupManageDialog.prototype.initPerm = function(te){
        var perm = te['perm'];        
        if(!ChatGroupPerm.check(perm, ChatGroupPerm.SHOWPARTICIPANTS)){ //show part
            this.$memPanel.hide();
        }        
        if(!ChatGroupPerm.check(perm, ChatGroupPerm.ADDPARTICIPANTS) || !ChatGroupPerm.check(perm, ChatGroupPerm.DELETEPARTICIPANTS)){
            this.memberSelector.readonly();
        }        
    };
    
    /**
     * 获取表单数据.
     */
    _groupManageDialog.prototype.getFormData = function(){
        var _this = this;        
        var formData = ujs.browser.form.getValues(this.$wrapper),
            members = this.memberSelector.getUserAndGroup(),  
            isSingle = this.memberSelector.isSingleUser(),     
            //基础数据.        
            data = {
                type : isSingle ? 'singlechat' : 'adminchat',
                ugids : members['groups'],
                uids : members['users'].concat(ujs.util.session.getCurrentUserID())   
            }; 
                          
        if(!isSingle){            
            $.extend(data,
                {
                    auids : this.memberSelector.getAdmins().concat(ujs.util.session.getCurrentUserID()),
                    title : formData['title'],
                    description : formData['description']
                }
            );
        }
        if(this.config['mode'] != 'edit'){
            //编辑模式不显示props.  
            var propType = _this.optionSelectorGrouper.getValue();
            var propsArr = _this.optionSelectorGrouper2.getValues();            
                        
            var propsObj = {
                allowParticipant : true //默认允许查看Participant.
            };            
                        
            if(!propsArr.contains('not')){      //Do not allow individual chat              
                $.extend(propsObj, {
                    allowChat : true,
                });
            }
            if(propsArr.contains('allowLocation')){                    
                $.extend(propsObj, {
                    allowLocation : true
                });
            }
            
            if(propType == 'destruct'){
                $.extend(propsObj, {
                    allowDestruct : true                   
                });                               
            } else if(propType == 'broadcast'){
                $.extend(propsObj, {
                    allowBroadcast : true,
                    allowParticipant : false,
                    allowLocation : false, 
                    allowChat : !!(propsArr.contains('reply'))
                });                  
            }  
                      
            $.extend(data, ChatGroupPerm.props, propsObj);
        }        
        //chat group图标.
        var formData = Object.toFormData({
            chat : JSON.stringify(data)
        });
        if(!isSingle){                        
            this.iconObj.fillupImageFiles(formData, [[200,200]]);
        }        
        return formData;
    };

    //--------------------------------------------------------------------------------------------------
    
    _groupManageDialog.prototype.toggleAdvancedProps = function(isShow){   
        if(Type.isUndefined(isShow)){
            isShow = !this.memberSelector.isSingleUser();
        }
        if(isShow){
            this.$wrapper.find('.flagFields').show();
            this.$selectUserTip.show();
            this.switchDialogButtons(['next']);    
            this.setTitle(this.config['title'] + ' 1/2');        
        } else {
            this.$wrapper.find('.flagFields').hide();
            this.$selectUserTip.hide();
            this.memberSelector.clearAdmins();
            this.switchDialogButtons(['save']);
            this.setTitle(this.config['title']);
        }        
        if(!this.memberSelector.getMembers().length){
            this.switchDialogButtons([]);
        }
    };
            
    return _groupManageDialog;    
})();